package de.openlaboratory.labhub.core.framework;

import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import de.openlaboratory.labhub.core.extension.Plugin;
import de.openlaboratory.labhub.core.extension.StandardPlugin;
import de.openlaboratory.labhub.core.framework.RuntimeFactory.LabHubCommand;
import de.openlaboratory.labhub.core.model.LabHubDataObject;

public class Command
{
	private LabHubCommand command;
	private String applicationName;
	private String applicationNamespace;
	private String objectType;
	private Collection<LabHubDataObject> dataObjects;

	public Command(String commandName)
	{
		this.command = getCommand(commandName);	
	}
	
	private LabHubCommand getCommand(String commandName)
	{
		for (LabHubCommand c : LabHubCommand.values())
		{
			if (c.name().equals(commandName))
			{
				return c;
			}
		}

		return LabHubCommand.CUSTOM;
	}

	public String execute(HttpServletRequest request)
	{
		Plugin p = getPlugin(applicationNamespace);
		
		if (p!=null)
		{
			for (LabHubDataObject lhdo : dataObjects)
			{
				p.execute(lhdo, command);
			}
		}
		
		return null;
	}
	
	public Plugin getPlugin(String className)
	{
		Plugin p = null;

		try
		{
			Class<?> c = Class.forName(className);
			if (StandardPlugin.class.isAssignableFrom(c))
			{
				try
				{
					p = (Plugin) c.newInstance();
				}
				catch (InstantiationException e)
				{
					e.printStackTrace();
				}
				catch (IllegalAccessException e)
				{
					e.printStackTrace();
				}
			}
		}
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}

		return p;
	}
}
